﻿<!DOCTYPE HTML>
<html lang="zh">
<head>
<title>#If - 语法 &amp; 使用 | AutoHotkey v2</title>
<meta name="description" content="The #If directive creates context-sensitive hotkeys and hotstrings. Such hotkeys perform a different action (or none at all) depending on the result of an expression." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
<script type="text/javascript">$(function(){0<=window.navigator.userAgent.toLowerCase().indexOf("ucbrowser")&&CaoNiMaDeUc()})</script>
</head>
<body>


<h1>#If</h1>

<p>创建上下文相关的<a href="../Hotkeys.htm">热键</a>和<a href="../Hotstrings.htm">热字串</a>. 这样的热键会根据表达式的结果执行不同的操作(或什么都不做).</p>

<pre class="Syntax"><span class="func">#If</span> <span class="optional">Expression</span></pre>
<h2 id="Parameters">参数</h2>
<dl>

  <dt>Expression</dt>
  <dd>
    <p>类型: <a href="../Concepts.htm#boolean">布尔值</a></p>
    <p>任何有效的<a href="../Variables.htm#Expressions">表达式</a>.</p>
  </dd>

</dl>

<h2 id="howto">基本操作</h2>
<p>The #If directive sets the expression which will be used by subsequently created hotkeys to determine whether they should activate. This expression is evaluated when the key, mouse button or combination is pressed, or at other times when the program needs to know whether the hotkey is active.</p>
<p>To make context-sensitive <a href="../Hotkeys.htm">hotkeys</a> and <a href="../Hotstrings.htm">hotstrings</a>, simply precede them with the #If directive. 例如:</p>
<pre>#If WinActive("ahk_class Notepad") or WinActive(MyWindowTitle)
#Space::MsgBox "You pressed Win+Spacebar in Notepad or " MyWindowTitle</pre>
<p>The #If directive is positional: it affects all hotkeys and hotstrings physically beneath it in the script, until the next #If directive.</p>
<p class="warning"><strong>Note:</strong> Unlike <a href="If.htm">if statements</a>, braces have no effect with the #If directive.</p>
<p>To turn off context sensitivity, specify #If without any expression. 例如:</p>
<pre>#If</pre>
<p>When a mouse or keyboard hotkey is disabled via #If, it performs its native function; that is, it passes through to the active window as though there is no such hotkey. There is one exception: Joystick hotkeys: although #If works, it never prevents other programs from seeing the press of a button.</p>
<p>#If can also be used to alter the behavior of an ordinary key like <kbd>Enter</kbd> or <kbd>Space</kbd>. This is useful when a particular window ignores that key or performs some action you find undesirable. 例如:</p>
<pre>#If WinActive("Reminders ahk_class #32770")  <em>; The "reminders" window in Outlook.</em>
Enter::Send "!o"  <em>; Have an &quot;Enter&quot; keystroke open the selected reminder rather than snoozing it.</em>
#If</pre>

<h2 id="variant">变体(Duplicate) 热键</h2>
<p>A particular <a href="../Hotkeys.htm">hotkey</a> or <a href="../Hotstrings.htm">hotstring</a> can be defined more than once in the script if each definition has different #If criteria. These are known as <em>hotkey variants</em>. 例如:</p>
<pre>#If <a href="WinActive.htm">WinActive</a>("ahk_class Notepad")
^!c::MsgBox "You pressed Control+Alt+C in Notepad."
#If WinActive("ahk_class WordPadClass")
^!c::MsgBox "You pressed Control+Alt+C in WordPad."
#If
^!c::MsgBox "You pressed Control+Alt+C in a window other than Notepad/WordPad."</pre>
<p>If more than one variant is eligible to fire, only the one closest to the top of the script will fire. The exception to this is the global variant (the one with no #If criteria): It always has the lowest precedence; therefore, it will fire only if no other variant is eligible (this exception does not apply to <a href="../Hotstrings.htm">hotstrings</a>).</p>
<p>When creating duplicate hotkeys, the order of <a href="../Hotkeys.htm#Symbols">modifier symbols</a> such as ^!+# does not matter. 例如, <code>^!c</code> is the same as <code>!^c</code>. However, keys must be spelled consistently. 例如, <em>Esc</em> is not the same as <em>Escape</em> for this purpose (though the case does not matter). Also, any hotkey with a <a href="../Hotkeys.htm#wildcard">wildcard prefix (*)</a> is entirely separate from a non-wildcard one; 例如, <code>*F1</code> and <code>F1</code> would each have their own set of variants.</p>
<p>To have the same hotkey subroutine executed by more than one variant, the easiest way is to create a stack of identical hotkeys, each with a different #If directive above it. 例如:</p>
<pre>#If WinActive("ahk_class Notepad")
#z::
#If WinActive("ahk_class WordPadClass")
#z::
MsgBox "You pressed Win+Z in either Notepad or WordPad."
return</pre>
<p>Alternatively, a <a href="GroupAdd.htm">window group</a> can be used via <code>#If WinActive("ahk_group MyGroup")</code>.</p>
<p>To create hotkey variants dynamically (while the script is running), 请参阅 <a href="Hotkey.htm#if">Hotkey "If"</a>.</p>

<h2 id="expression-evaluation">Expression Evaluation</h2>
<p>When the key, mouse or joystick button combination which forms a hotkey is pressed, the #If expression is evaluated to determine if the hotkey should activate.</p>
<p class="warning"><strong>Note:</strong> Scripts should not assume that the expression is only evaluated when the key is pressed (see below).</p>
<p>The expression may also be evaluated whenever the program needs to know whether the hotkey is active. 例如, the #If expression for a custom combination like <code>a &amp; b::</code> might be evaluated when the prefix key (<code>a</code> in this example) is pressed, to determine whether it should act as a custom modifier key.</p>
<p class="warning" id="lag"><strong>Note:</strong> Use of #If in an unresponsive script may cause input lag or break hotkeys (see below).</p>
<p>There are several more caveats to the #If directive:</p>
<ul>
  <li>Keyboard or mouse input is typically buffered (delayed) until expression evaluation completes or <a href="_IfTimeout.htm">times out</a>.</li>
  <li>Expression evaluation can only be performed by the script's main thread (at the OS level, not a <a href="../misc/Threads.htm">quasi-thread</a>), not directly by the keyboard/mouse hook. If the script is busy or unresponsive, such as if a FileCopy is in progress, expression evaluation is delayed and may time out.</li>
  <li>If the <a href="_IfTimeout.htm#LowLevelHooksTimeout">system-defined timeout</a> is reached, the system may stop notifying the script of keyboard or mouse input (see #IfTimeout for details).</li>
  <li>Sending keystrokes or mouse clicks while the expression is being evaluated (such as from a function which it calls) may cause complications and should be avoided.</li>
</ul>
<p><a href="../Variables.htm#ThisHotkey">A_ThisHotkey</a> and <a href="../Variables.htm#TimeSinceThisHotkey">A_TimeSinceThisHotkey</a> are set based on the hotkey for which the current #If expression is being evaluated.</p>
<p><a href="../Variables.htm#PriorHotkey">A_PriorHotkey</a> and <a href="../Variables.htm#TimeSincePriorHotkey">A_TimeSincePriorHotkey</a> temporarily contain the previous values of the corresponding "This" variables.</p>

<h2 id="optimization">Optimization</h2>
<p>#If is optimized to avoid expression evaluation for simple calls to <a href="WinActive.htm">WinActive</a> or <a href="WinExist.htm">WinExist</a>, thereby reducing the <a href="#lag">risk of lag</a> or other issues in such cases. Specifically:</p>
<ul>
  <li>The expression must contain exactly one call to <a href="WinExist.htm">WinExist</a> or <a href="WinActive.htm">WinActive</a>.</li>
  <li>Each parameter must be a single quoted string, and no more than two parameters may be used.</li>
  <li>The result may be inverted with <code>not</code> or <code>!</code>, but no other operators may be used.</li>
  <li>Whitespace and parentheses are fully handled when the expression is pre-compiled and therefore do not affect this optimization.</li>
</ul>
<p>If the expression meets these criteria, it is evaluated directly by the program and does not appear in <a href="ListLines.htm">ListLines</a>.</p>
<p>Before the <a href="Hotkey.htm">Hotkey</a> function is used to modify an existing hotkey variant, typically <code>Hotkey "If"</code> must be used with the original expression text. However, the first unique expression with a given combination of criteria can also be referenced by that criteria. 例如:</p>
<pre>
Hotkey "IfWinExist", "ahk_class Notepad"
Hotkey "#n", "Off"  <em>; Turn the hotkey off.</em>
Hotkey 'If', 'WinExist("ahk_class Notepad")'
Hotkey "#n", "On"   <em>; Turn the same hotkey back on.</em>

#if WinExist("ahk_class Notepad")
#n::WinActivate
</pre>
<p>Note that any use of variables will disqualify the expression. If the variable's value never changes after the hotkey is created, there are two strategies for minimizing the risk of lag or other issues inherent to #If:</p>
<ul>
  <li>Use <code><a href="Hotkey.htm#IfWin">Hotkey "IfWin..."</a>, MyTitleVar</code> to set the criteria and <code><a href="Hotkey.htm">Hotkey</a> KeyName, Label</code> to create the hotkey variant.</li>
  <li>Use a constant expression such as <code>#if WinActive("ahk_group MyGroup")</code> and define the window group with <code><a href="GroupAdd.htm">GroupAdd</a> "MyGroup", MyTitleVar</code> elsewhere in the script.</li>
</ul>

<h2 id="general-remarks">备注</h2>
<p>#If also restores prefix keys to their native function when appropriate (a <a href="../Hotkeys.htm#prefix">prefix key</a> is the <kbd>A</kbd> key in a hotkey such as <code>a &amp; b</code>). This occurs whenever there are no enabled hotkeys for a given prefix.</p>
<p>When Gosub or Goto is used to jump to a hotkey or hotstring label, it jumps to the variant closest to the top of the script.</p>
<p>When a hotkey is currently disabled via #If, its key or mouse button will appear with a "#" character in <a href="KeyHistory.htm">KeyHistory's</a> "Type" column. This can help debug a script.</p>
<p><a href="../Hotkeys.htm#alttab">Alt-tab hotkeys</a> are not affected by #If: they are in effect for all windows.</p>
<p>The <a href="../misc/WinTitle.htm#LastFoundWindow">Last Found Window</a> can be set by #If. 例如:</p>
<pre>#If <a href="WinExist.htm">WinExist</a>("ahk_class Notepad")
#n::<a href="WinActivate.htm">WinActivate</a>  <em>; Activates the window found by WinExist().</em></pre>

<h2 id="Related">相关</h2>
<p><a href="_IfTimeout.htm">#IfTimeout</a> may be used to override the default timeout value.</p>
<p><a href="Hotkey.htm">Hotkey function</a>, <a href="../Hotkeys.htm">Hotkeys</a>, <a href="../Hotstrings.htm">Hotstrings</a>, <a href="Suspend.htm">Suspend</a>, <a href="WinActive.htm">WinActive</a>, <a href="WinExist.htm">WinExist</a>, <a href="SetTitleMatchMode.htm">SetTitleMatchMode</a>, <a href="DetectHiddenWindows.htm">DetectHiddenWindows</a></p>

<h2 id="Examples">示例</h2>

<div class="ex" id="ExVolume">
<p><a href="#ExVolume">#1</a>: Adjust volume by scrolling the mouse wheel over the taskbar:</p>
<pre>
<em>; 示例 0: WinActive.</em>
#If WinActive("ahk_class Notepad")
^!a::MsgBox "You pressed Ctrl-Alt-A while Notepad is active."
#c::MsgBox "You pressed Win-C while Notepad is active."
::btw::This replacement text for "btw" will occur only in Notepad.
#If
#c::MsgBox "You pressed Win-C in a window other than Notepad."

#If MouseIsOver("ahk_class Shell_TrayWnd")
WheelUp::Send "{Volume_Up}"
WheelDown::Send "{Volume_Down}"

MouseIsOver(WinTitle) {
    MouseGetPos ,, Win
    return WinExist(WinTitle " ahk_id " Win)
}
</pre>
</div>

<div class="ex" id="ExWordDelete">
<p><a href="#ExWordDelete">#2</a>: Simple word-delete shortcuts for all Edit controls:</p>
<pre>
#If ActiveControlIsOfClass("Edit")
^BS::Send "^+{Left}{Del}"
^Del::Send "^+{Right}{Del}"

ActiveControlIsOfClass(Class) {
    FocusedControl := ControlGetFocus("A")
    FocusedControlClass := WinGetClass("ahk_id " FocusedControl)
    return (FocusedControlClass=Class)
}
</pre>
</div>

<div class="ex" id="ExContextInsens">
<p><a href="#ExContextInsens">#3</a>: Context-insensitive Hotkey.</p>
<pre>
#If
Esc::ExitApp
</pre>
</div>

<div class="ex" id="ExDynamic">
<p><a href="#ExDynamic">#4</a>: Dynamic Hotkeys. This example requires the MousIsOver function from <a href="#ExVolume">example #1</a>:</p>
<pre>
NumpadAdd::
Hotkey "If", 'MouseIsOver("ahk_class Shell_TrayWnd")'
if (doubleup := !doubleup)
    Hotkey "WheelUp", "DoubleUp"
else
    Hotkey "WheelUp", "WheelUp"
return

DoubleUp:
Send "{Volume_Up 2}"
return
</pre>
</div>

</body>
</html>